var publicMethods = {}; 

// 登陆检查
checkLogin = function(uid){
  if (!uid) {
    throw new Meteor.Error('未登陆','请您先登录！');
  }
};
// 权限检查
checkPermission = function(uid,funcName){
  if (!Roles.userIsInRole(uid, funcName)) {
    throw new Meteor.Error(10012-0,'抱歉，权限不足！');
  }
};

// 所属公司检查
checkCompany = function(uid,cid){
  var user = Meteor.users.findOne(uid,{_id: 0,'company_id':1});
  // var theCompany = Companies.findOne(user.company_id);
  if (user.company_id !== cid){
    throw new Meteor.Error(10012, "错误：无法修改别家公司信息!");
  }
};


Meteor.methods({

  /**
   * 添加员工子账号
   */
  addUser:function(newUser){
    checkLogin(this.userId);
    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1, 'profile.pmsn_group':1});
    var company = Companies.findOne(user.company_id);
    var childUsersCount = Meteor.users.find({'company_id':user.company_id}).count();

    if (childUsersCount >= company.users_num){
      throw new Meteor.Error(10010, "账号数量已用尽，无法继续添加!");
    }

    newUser.company_id = user.company_id;

    try {
      newUserId = Meteor.users.insert(newUser);
      // TODO
      // Roles.addUsersToRoles();
    } catch (e) {
      if (e.name !== 'MongoError') throw e;
      if (e.code !== 11000) throw e;
      if (e.err.indexOf('name') !== -1) throw new Meteor.Error(403, "用户名已存在.");
      throw e;
    }
    Accounts.setPassword(newUserId, '888888');
    return newUserId;
  },


  /**
   * 更新员工账号信息
   */
  updateUser:function(userToUpdate){
    checkLogin(this.userId);

    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1, 'profile.pmsn_group':1});
    var theUser = Meteor.users.findOne(userToUpdate._id,{'company_id':1});
    checkCompany(this.userId,theUser.company_id);

    try {
      theUserToUpdateId = Meteor.users.update({'_id':userToUpdate._id},
        { $set: {
          'emails':userToUpdate.emails,
          'profile':userToUpdate.profile} });
    } catch (e) {
      if (e.name !== 'MongoError') throw e;
      if (e.code !== 11000) throw e;
      throw e;
    }
    return theUserToUpdateId;
  },
  /**
   * 删除用户
   */
  // deleteUser:function(theUserId){
  //   checkLogin(this.userId);

  //   var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1, 'profile.pmsn_group':1});
  //   var theUser = Meteor.users.findOne(theUserId,{_id: 0,'company_id':1});
  //   if (user.company_id !== theUser.company_id){
  //     throw new Meteor.Error(10013, "该用户不属于您的公司，无法删除!");
  //   }

  //   try {
  //     return Meteor.users.remove(theUserId);
  //   } catch (e) {
  //     throw e;
  //   }
  // },


  /**
   * 强制重置用户密码
   */
  resetUserPw:function(data){
    checkLogin(this.userId);

    if(!data._id){
      throw new Meteor.Error('invalid','指定的账号无效。');
    }
    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1, 'profile.pmsn_group':1});
    var theUser = Meteor.users.findOne(data._id,{_id: 0,'company_id':1});
    if (user.company_id !== theUser.company_id){
      throw new Meteor.Error(10014, "该用户不属于您的公司，无法修改密码!");
    }

    try {
      Accounts.setPassword(data._id, data.password);
    } catch (e) {
      throw e;
    }
  },

  /**
   * 更新用户在职状态
   */
  updateEmployeeState:function(data){
    checkLogin(this.userId);
    var theUser = Meteor.users.findOne(data.uid,{'company_id':1,'state':1,'profile.state':1});
    checkCompany(this.userId,theUser.company_id);
    var accountState = '';
    switch(data.state){
      case '在职':
        accountState = '已启用';
        break;
      case '休假中':
        accountState = '锁定中';
        break;
      case '离职':
        accountState = '已停用';
        break;
    }
    try {
      theUserId = Meteor.users.update({'_id':data.uid}, { $set: { state:accountState,'profile.state':data.state } });
    } catch (e) {
      throw e;
    }
    return theUserId;
  },
  switchUser:function(uid){
    checkLogin(this.userId);
    var theUser = Meteor.users.findOne(uid,{'company_id':1,'state':1});
    checkCompany(this.userId,theUser.company_id);
    var newState = '';
    if(theUser.state=='未启用'){
      newState = '已启用';
    }else if(theUser.state=='已启用'){
      newState = '未启用';
    }

    try {
      theUserId = Meteor.users.update(uid, { $set: { state:newState} });
    } catch (e) {
      throw e;
    }
    return theUserId;
  },

  /**
   * 添加部门
   */
  addDept:function(newDept){
    checkLogin(this.userId);

    var user = Meteor.users.findOne(this.userId);
    newDept.company_id = user.company_id;
    if(newDept.type=='sm' && !newDept.parent_id){
      var abstractStoreId = Departments.findOne({'type':'store-collection'});
      if(!abstractStoreId){
        var abstractStore = {
          company_id:user.company_id,
          type:'store-collection',
          name:'门店',
          remark:''
        };
        try {
          abstractStoreId = Departments.insert(abstractStore);
        } catch (e) {
          throw e;
        }
      }
      newDept.parent_id = abstractStoreId;
    }
    try {
      theDeptId = Departments.insert(newDept);
    } catch (e) {
      throw e;
    }
    return theDeptId;
  },
  updateDept:function(theDept){
    checkLogin(this.userId);

    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1});
    // var theDept = Departments.findOne(deptId);
    if (user.company_id !== theDept.company_id){
      throw new Meteor.Error(10022, "该部门不属于您的公司，无法修改!");
    }
    try {
      theDeptId = Departments.update({'_id':theDept._id}, theDept);
    } catch (e) {
      throw e;
    }
    return theDeptId;
  },
  /**
   * 删除部门
   */
  deleteDept:function(deptId){
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in','登陆后才能删除部门。');
    }
    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1});
    var theDept = Departments.findOne(deptId);
    if (user.company_id !== theDept.company_id){
      throw new Meteor.Error(10023, "该部门不属于您的公司，无法删除!");
    }
    return Departments.remove(deptId);
  },

  /**
   * 更新公司信息
   */
  updateCompanyInfo:function(theCompany){
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in','登陆后才能更新公司信息。');
    }

    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1});
    if (user.company_id !== theCompany._id){
      throw new Meteor.Error(10042, "错误：无法修改别家公司的信息!");
    }
    Companies.update(theCompany._id, { $set: { tel:theCompany.tel, address: theCompany.address} });
  },

  /**
   * 用户手动添加分类
   */
  addProductCata:function(catalog){
    var pcid='';
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in','登陆后才能添加分类。');
    }
    if (! catalog.name) {
      throw new Meteor.Error(10050,'分类名称不能为空。');
    }
    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1});
    catalog.company_id = user.company_id;
    try {
      pcid = ProductCatalogs.insert(catalog);
    } catch (e) {
      throw e;
    }
    return pcid;
  },
  /**
   * 更新商品分类
   */
  updateProductCata:function(catalog){
    checkLogin(this.userId);
    checkCompany(this.userId,catalog.company_id);
    try {
      ProductCatalogs.update({'_id':catalog._id}, { $set: { 'name':catalog.name, 'parent_id':catalog.parent_id} });
    } catch (e) {
      throw e;
    }
  },
  /**
   * 删除分类
   */
  deleteProductCata:function(catalogId){
    checkLogin(this.userId);
    var theCatalog = ProductCatalogs.findOne(catalogId,{'company_id':1});
    checkCompany(this.userId,theCatalog.company_id);
    try {
      pcid = ProductCatalogs.remove(catalogId);
    } catch (e) {
      throw e;
    }
    return pcid;
  },
  /**
   * 从默认分类导入分类
   */
  importProductCata:function(catalogs){
    if (! this.userId) {
      throw new Meteor.Error('not-logged-in','登陆后才能继续操作。');
    }
    if(!catalogs.length){
      return;
    }
    var user = Meteor.users.findOne(this.userId,{_id: 0,'company_id':1});

    catalogs.forEach(catalog=> {
      catalog.company_id = user.company_id;
      var isExist = ProductCatalogs.findOne({'cid':catalog.cid,'company_id':user.company_id});
      if (isExist==null){
        try {
          pcid = ProductCatalogs.insert(catalog);
        } catch (e) {
          throw e;
        }
      }else{
        // throw new Meteor.Error(10054,'该分类已存在，无需重复添加。');
      }
    });
    return pcid;
  },
  /**
   * 更新分类产品属性值
   */
  updateProductProperty:function(property){
    checkLogin(this.userId);
    var theCatalog = ProductCatalogs.findOne({_id:property.catalogId});
    checkCompany(this.userId,theCatalog.company_id);
    try {
      theCatalogUpdateId = ProductCatalogs.update({'_id':property.catalogId,'properties._id':property._id},
        { $set: { 'properties.$.value_set':property.value_set} });
      return theCatalogUpdateId;
    } catch (e) {
      throw e;
    }
  },

  /**
   * 增加供应商
   */
  addSupplier:function(newSupplier){
    checkLogin(this.userId);
    var user = Meteor.users.findOne(this.userId,{_id:0,'company_id':1,'profile.pmsn_group':1});
    if (!newSupplier.company) {
      throw new Meteor.Error(10060,'公司名称不能为空。');
    }
    newSupplier.company_id = user.company_id;
    try {
      newSid = Suppliers.insert(newSupplier);
    } catch (e) {
      throw e;
    }
    return newSid;
  },

  /**
   * 更新供应商信息
   */
  updateSupplier:function(theSupplier){
    checkLogin(this.userId);
    var supplier = Suppliers.findOne(theSupplier._id,{'company_id':1});
    checkCompany(this.userId,supplier.company_id);
    try {
      theSupplierToUpdateId = Suppliers.update({'_id':supplier._id},
        { $set: { 'category':theSupplier.category,
                  'company':theSupplier.company,
                  'address':theSupplier.address,
                  'tel':theSupplier.tel,
                  'contact_list':theSupplier.contact_list}
      });
    } catch (e) {
      throw e;
    }
  },

  /**
   * 删除供应商
   */
  deleteSupplier:function(supplierId){
    checkLogin(this.userId);
    var supplier = Suppliers.findOne(supplierId,{'company_id':1});
    checkCompany(this.userId,supplier.company_id);
    try {
      sid = Suppliers.remove(supplierId);
    } catch (e) {
      throw e;
    }
    return sid;
  },
  /**
   * 星标供应商  TODO 未完成
   */
  starSupplier:function(supplierId){
    checkLogin(this.userId);
    var supplier = Suppliers.findOne(supplierId,{'company_id':1});
    checkCompany(this.userId,supplier.company_id);
    try {
      sid = Suppliers.update(supplierId, { $set: { order:0 } });
    } catch (e) {
      throw e;
    }
    return sid;
  },

  importSupplier:function(suppliers){
    checkLogin(this.userId);
    var user = Meteor.users.findOne(this.userId,{_id:0,'company_id':1});

    suppliers.forEach(function(supplier){
      supplier.company_id = user.company_id;
      try {
        sid = Suppliers.insert(supplier);
      } catch (e) {
        throw e;
      }
    });
    // return sid;
  },


/**
 * 创建采购单
 */
  createPurchaseOrder:function(newPurchaseOrder){
    checkLogin(this.userId);
    var user = Meteor.users.findOne(this.userId,{_id:0,'company_id':1,'profile.pmsn_group':1});
    if (!newPurchaseOrder.supplier) {
      throw new Meteor.Error(10070,'供应商不能为空。');
    }
    newPurchaseOrder.company_id = user.company_id;
    newPurchaseOrder.order_no = 'JH'+moment().unix();
    newPurchaseOrder.date = moment().toDate();
    try {
      newPOId = Purchase.insert(newPurchaseOrder);
    } catch (e) {
      throw e;
    }
    return newPOId;
  },
  /**
   * 更新采购单状态
   */
  updatePOState:function(stateData){
    checkLogin(this.userId);
    var theOrder = Purchase.findOne(stateData.order_id);
    checkCompany(this.userId,theOrder.company_id);
    if(theOrder.state===0 || theOrder.state===5){
      throw new Meteor.Error(10074,theOrder.state_history[theOrder.state_history.length-1].operation.note+'的订单不允许更改状态。');
    }
    try {
      thePOId = Purchase.update(stateData.order_id, {$set:{state:stateData.state.operation.note}, $push: { state_history: stateData.state } });
    } catch (e) {
      throw e;
    }
    return thePOId;
  },
  /**
   * 更新付款
   */
  updatePOpaid:function(paidData){
    checkLogin(this.userId);
    var theOrder = Purchase.findOne(paidData.order_id);
    checkCompany(this.userId,theOrder.company_id);

  }

});
